<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Pagination } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/pagination'
const { proxy } = getCurrentInstance()

/* ---- */
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  title: '',
  // ----
  share_title: proxy.$shareTitle,
  share_desc: proxy.$shareDesc,
  share_icon: proxy.$shareIcon
})
// ----
const forFree = 1
const setTrueStyle = ref({})
const forPagination = {
  type: 'fraction'
}
const modules = [Pagination]
// ----
const pdt = reactive({
  name: '',
  content: '',
  proremark: '',
  price: {
    name: '',
    cloudprice: '',
    price: '',
    unit: ''
  },
  sizes: [],
  topImgs: [],
  fotImgs: [],
  // ----
  isFromCloud: false
})
// ----
const items = ref([])

/* ---- */
const preImg = ref()
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// --设置微信分享--
const setWebShare = (info) => {
  const forSn = proxy.$Store.get('SN')
  const currentUrl = window.location.href.split('#')[0]
  const shareLink = (Number(currentUrl.indexOf('sn=')) === Number(-1)) ? ((Number(currentUrl.indexOf('?')) === Number(-1)) ? currentUrl + '?sn=' + forSn : currentUrl + '&sn=' + forSn) : currentUrl
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.hideMenuItem()
    obj.showMenuList(['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite', 'menuItem:share:QZone'])
    // ----
    obj.share({
      title: info.title,
      desc: info.desc,
      link: shareLink,
      imgUrl: info.imgUrl
    })
  })
}
// ----
const getTrueStyle = () => {
  if (proxy.$refs.forTrueWidth) {
    const imgEL = proxy.$refs.forTrueWidth
    const imgRatio = forFree
    setTrueStyle.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
// ----
const getCurrencyInfo = async () => {
  // --获取用户信息 & 计量单位 & 商品详情 --
  const forUserData = { params: { 'DealerSearch[id]': proxy.$route.query.dealer_id } }
  const forUnitData = {
    params: {
      'MeasuringUnitSearch[dealer_id]': proxy.$route.query.dealer_id,
      // --是否云仓计量单位--
      'MeasuringUnitSearch[is_store]': 1,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forGoodsData = { params: { 'ProductSearch[id]': proxy.$route.query.goods_id } }
  await proxy.$Axios.all([
    proxy.$Axios.get('dealer/index', forUserData),
    proxy.$Axios.get('measuring-unit/index', forUnitData),
    proxy.$Axios.get('proc/index', forGoodsData)
  ]).then(proxy.$Axios.spread((userData, unitData, goodsData) => {
    // --用户信息--
    const UData = userData.items[0] || {}
    user.title = proxy.$Myfun.setText(UData.name)
    if (UData.name) user.share_desc = proxy.$Myfun.setText(UData.name)
    proxy.$Myfun.getJsonData(UData.avatar, (resJson) => {
      if (Number(resJson.length) > 0) user.share_icon = resJson[0].image
    })
    // --计量单位--
    const unitItems = []
    unitData.items.forEach((item, index) => {
      unitItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    // --商品详情--
    if (goodsData.items && Number(goodsData.items.length) > 0) {
      const GData = goodsData.items[0]
      // ----
      let forSize = []
      const cloudItems = []
      const saleItems = []
      proxy.$Myfun.getJsonData(GData.price_json, (resJson) => { forSize = resJson })
      forSize.forEach((item) => {
        cloudItems.push(item.cloudprice)
        saleItems.push(item.price)
      })
      let forCloud = ''
      const cloudMax = Math.max.apply(null, cloudItems)
      const cloudMin = Math.min.apply(null, cloudItems)
      if (Number(cloudMax) > Number(cloudMin)) {
        forCloud = cloudMin.toFixed(2) + '-' + cloudMax.toFixed(2)
      } else { forCloud = cloudMin.toFixed(2) }
      let forSale = ''
      const saleMax = Math.max.apply(null, saleItems)
      const saleMin = Math.min.apply(null, saleItems)
      if (Number(saleMax) > Number(saleMin)) {
        forSale = saleMin.toFixed(2) + '-' + saleMax.toFixed(2)
      } else { forSale = saleMin.toFixed(2) }
      // ----
      const imgTopArr = []
      proxy.$Myfun.getJsonData(GData.img_top, (resJson) => {
        resJson.forEach(function (item, index) {
          imgTopArr.push({
            msrc: item.image,
            src: item.image,
            width: item.width,
            height: item.height,
            alt: ''
          })
        })
      })
      const imgFotArr = []
      proxy.$Myfun.getJsonData(GData.img_bot, (resJson) => {
        resJson.forEach(function (item, index) {
          imgFotArr.push({
            msrc: item.image,
            src: item.image,
            width: item.width,
            height: item.height,
            alt: ''
          })
        })
      })
      // ----
      if (GData.name) user.share_title = proxy.$Myfun.setText(GData.name)
      pdt.name = proxy.$Myfun.setText(GData.name)
      pdt.content = GData.content
      pdt.proremark = proxy.$Myfun.setText(GData.proremark_id)
      pdt.price.cloudprice = forCloud
      pdt.price.price = forSale
      pdt.sizes = forSize
      pdt.topImgs = imgTopArr
      pdt.fotImgs = imgFotArr
      pdt.isFromCloud = Number(GData.is_type) === 1
      // ----
      unitItems.some((current) => {
        if (String(current.value) === String(forSize[0].unit)) pdt.price.unit = current.text
      })
    } else { proxy.$Myfun.forToast(layer.value, 'open', '该商品已经下架啦！！！', () => { proxy.$router.back() }) }
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // --设置微信分享信息--
  const forShare = {
    title: user.share_title,
    desc: user.share_desc,
    imgUrl: user.share_icon
  }
  setWebShare(forShare)
  // ----
  items.value = [{
    show: true,
    name: '下载材质书',
    class: 'xw-bgCL-11 xw-act',
    callback: () => {
      proxy.$Myfun.openPage(proxy, 'push', 'MaterialCreate', { id: proxy.$route.query.id, dealer_id: proxy.$route.query.dealer_id, goods_id: proxy.$route.query.goods_id })
    }
  }]
}
// ----
const getAuditFun = (type, item, event, index) => {
  switch (Number(type)) {
    case 1: {
      const curEL = event.currentTarget
      const options = {
        actElement: curEL,
        addopt: {
          index: Number(index) || 0,
          loop: true,
          dataSource: item
        }
      }
      proxy.$Myfun.isIndepth(preImg.value, 'openPhotoSwipe', options)
      break
    }
    case 2: {
      pdt.price.name = item.name
      pdt.price.cloudprice = Number(item.cloudprice).toFixed(2)
      pdt.price.price = Number(item.price).toFixed(2)
      break
    }
    case 3: {
      item.callback && item.callback()
      break
    }
  }
}

/* ---- */
onMounted(() => {
  setTimeout(() => { getTrueStyle() }, 100)
  // ----
  getCurrencyInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch PDV-view xw-bg-white" ref="formSection">
    <div class="PDV-top">
      <div class="list-li"><div ref="forTrueWidth"></div></div>
      <swiper :modules="modules" :pagination="forPagination" :style="setTrueStyle" class="PDV-banner" v-if="pdt.topImgs && Number(pdt.topImgs.length) > 0">
        <swiper-slide v-for="(item, index) in pdt.topImgs" @click="getAuditFun(1, pdt.topImgs, $event, index)"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.src + ')' }"></div></swiper-slide>
      </swiper>
      <div class="PDV-title">{{pdt.name}}</div>
      <template v-if="pdt.price && Number(Object.keys(pdt.price).length) > 0">
        <template v-if="pdt.isFromCloud">
          <div class="PDV-price xw-flex xw-flex-align">
            <span>销售参考价：</span>
            <div class="xw-color-11">{{pdt.price.price}}</div>
            <span>元</span>
            <span v-if="pdt.price.unit">/{{pdt.price.unit}}</span>
          </div>
          <div class="PDV-price xw-flex xw-flex-align">
            <span>分销进货价：</span>
            <div class="xw-color-11">{{pdt.price.cloudprice}}</div>
            <span>元</span>
            <span v-if="pdt.price.unit">/{{pdt.price.unit}}</span>
          </div>
        </template>
        <template v-else >
          <div class="PDV-price xw-flex xw-flex-align">
            <span>销售价格：</span>
            <div class="xw-color-11">{{pdt.price.price}}</div>
            <span>元</span>
            <span v-if="pdt.price.unit">/{{pdt.price.unit}}</span>
          </div>
        </template>
      </template>
      <div class="PDV-size xw-Tfg" v-if="pdt.sizes && Number(pdt.sizes.length) > 0">
        <div class="PDV-size-title">型号规格</div>
        <div class="PDV-size-con xw-flex xw-flex-wrap">
          <span v-for="(item, index) in pdt.sizes" :class="['xw-radius-3 xw-ellipsis xw-anim', String(pdt.price.name) === String(item.name) ? 'active' : '']" @click="getAuditFun(2, item)">{{item.name}}</span>
        </div>
      </div>
      <div class="PDV-note xw-color-19 xw-bgCL-19 xw-radius-3" v-if="pdt.proremark">{{pdt.proremark}}</div>
    </div>
    <div class="PDV-center" v-if="pdt.content">
      <div class="PDV-desc" v-html="pdt.content"></div>
    </div>
    <div class="PDV-fot" v-if="pdt.fotImgs && Number(pdt.fotImgs.length) > 0">
      <ul class="PDV-advs">
        <li v-for="(item, index) in pdt.fotImgs" @click="getAuditFun(1, pdt.fotImgs, $event, index)"><img :src="item.src"></li>
      </ul>
    </div>
    <footer>
      <div class="tabs TAB-dbtn xw-foot-Tfg xw-flex xw-flex-align">
        <template v-for="(item, index) in items">
          <div class="xw-radius-3 xw-flex-W1 xw-flex xw-flex-center" @click="getAuditFun(3, item)" :class="item.class" v-if="item.show"><em :class="item.icon"></em>{{item.name}}</div>
        </template>
      </div>
    </footer>
    <preImg-view ref="preImg"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
  </div>
</template>

<style scoped>
/* ---- */
.PDV-view { padding: 0 0 6.4rem; }
.PDV-title { margin: 1.4rem 1rem 0; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; text-align: justify; word-break: break-all; word-wrap: break-word; }
.PDV-price { margin: 0.5rem 1rem 0; font-size: 1.5rem; }
.PDV-price div { font-size: 1.7rem; }
.PDV-size { margin: 1.4rem 0 0; }
.PDV-size:before { left: 1rem; right: 1rem; }
.PDV-size-title { padding: 1.4rem 1rem 0; font-size: 1.5rem; }
.PDV-size-con { padding: 0 0.5rem; }
.PDV-size-con span { margin: 1rem 0.5rem 0; padding: 0 1rem; height: 3rem; line-height: 3rem; background: #f5f5f5; border-radius: 1.5rem; }
.PDV-size-con span.active { background: #ff5722; color: #ffffff; }
.PDV-note { margin: 1.4rem 1rem 0; padding: 0.8rem 1rem; line-height: 2.5rem; text-align: justify; word-break: break-all; word-wrap: break-word; }
.PDV-desc { padding: 1.4rem 1rem; line-height: 2.5rem; font-size: 1.6rem; text-align: justify; }
.PDV-advs { padding: 1.4rem 0; }
.PDV-advs img { max-width: 100%; }
</style>
<style>
/* ---- */
.PDV-banner { background: #f5f5f5; }
.PDV-banner .swiper-pagination-fraction { padding: 0 1rem; left: auto; right: 1rem; bottom: 1rem; width: auto; height: 2.4rem; line-height: 2.4rem; color: #ffffff; background: rgba(0, 0, 0, 0.5); border-radius: 1.2rem; }
</style>